package com.company.cloud.goodsrestservice.service.impl;

import com.company.cloud.goodsrestservice.core.AbstractService;
import com.company.cloud.goodsrestservice.dao.GoodsMapper;
import com.company.cloud.goodsrestservice.model.Goods;
import com.company.cloud.goodsrestservice.service.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * Created by reabout on 2018/03/24.
 */
@Service
@Transactional
public class GoodsServiceImpl extends AbstractService<Goods> implements GoodsService {
    @Resource
    private GoodsMapper goodsCommonMapper;

    private final Logger log = LoggerFactory.getLogger(GoodsService.class);

    public Goods chkInsert(String goodsNumber, float priceJd, float priceOff, float priceEu, float priceSup) {
        Goods goods = findBy("goodsNumber", goodsNumber);
        if (goods == null & goodsNumber!="") {
            log.info("New goods {}", goodsNumber);
            goods = new Goods();
            goods.setGoodsNumber(goodsNumber);
            goods.setPriceJd(priceJd);
            goods.setPriceOffical(priceOff);
            goods.setPriceOfficalEu(priceEu);
            goods.setPriceSupply(priceSup);
            Long now = System.currentTimeMillis();
            goods.setCreateTime(now);
            goods.setUpdateTime(now);
            if (priceSup > 0 & priceOff > 0) {
                goods.setGoodsDiscountRate(priceSup/priceOff);
            } else {
                goods.setGoodsDiscountRate(null);
            }
            save(goods);
            goods = findBy("goodsNumber", goodsNumber);
        } else {
            Boolean new_price = false;
            if (priceOff > 0 & priceOff != goods.getPriceOffical()) {
                new_price = true;
                goods.setPriceOffical(priceOff);
            }
            if (priceEu > 0 & priceEu != goods.getPriceOfficalEu()) {
                new_price = true;
                goods.setPriceOfficalEu(priceEu);
            }
            if (priceSup > 0 & priceSup != goods.getPriceSupply()) {
                goods.setPriceSupply(priceSup);
                new_price = true;
            }
            if (priceJd > 0 & priceJd != goods.getPriceJd()) {
                new_price = true;
                goods.setPriceJd(priceJd);
            }
            if (new_price) {
                Long now = System.currentTimeMillis();
                goods.setUpdateTime(now);
                update(goods);
            }
        }
        return goods;
    }
}
